/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: MyAuthenticationSuccessHandler
 * Author:   吴建森
 * Date:     2020/12/6 17:26
 * Description:
 * History:
 * <author>吴建森      <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.sen.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sen.entity.EmpEntity;
import com.sen.entity.MenuEntity;
import com.sen.entity.MyUserDetails;
import com.sen.entity.RoleEntity;
import com.sen.service.EmpService;
import com.sen.service.MenuService;
import com.sen.service.RoleService;
import com.sen.utils.JwtTokenUtil;
import com.sen.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 吴建森
 * @create 2020/12/6
 * @since 1.0.0
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    EmpService empService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        MyUserDetails principal = (MyUserDetails) authentication.getPrincipal();
        //获取用户登录名称
        String username = principal.getUsername();
        //查询用户信息
        EmpEntity emp = empService.getOne(new QueryWrapper<EmpEntity>().eq("username", username));
        //通过用户名称查询用户角色
        RoleEntity role = roleService.getRoleByUsername(username);
        //获取角色查询对应菜单权限
        List<MenuEntity> menus = menuService.queryMenusByRole(role.getId());
        String name = objectMapper.writeValueAsString(
                R.ok()
                        .put("token", jwtTokenUtil.generateToken(principal))
                        .put("menus", menus)
                        .put("emp", emp)
        );
        writer.print(name);
        writer.flush();
        writer.close();
    }
}
